<template>
  <base-breadcrumb
    class="UpdateLeagueActivity-container fixed-container"
    :title="breadcrumbTitle"
  >
    <a-spin :spinning="!!loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="formInfo"
          :form-list="formItemList"
          @selectNode="handleSelectOrg"
        >
          <template v-slot:sectionTitle>
            <title-name title="活动信息" />
          </template>
          <template v-slot:fileIds>
            <l-table
              :disabled="isDisabled"
              :upload-arrys.sync="formInfo.fileIds"
              business-code="YOUTH01"
              upload-type="image"
              :edit-model="2"
            />
          </template>
        </custom-form>
        <title-name title="相关附件" />
        <UploadTableNew
          ref="uploadTable"
          :disabled="isDisabled"
          business-code="YOUTH02"
          :mode="pageType"
          :request-fn="getFileList"
        />
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { getDetail, getFiles, addData, editData } from '@/api/partyMasses/leagueManage/leagueActivity.js'
import Selector from '@/components/Select/Selector.vue'
import youthTreeSelect from '../../componments/youthTreeSelect.vue'
import Vue from 'vue'
import Moment from 'moment'
import { LEAGUE_TYPE_MAP } from '@/config/businessConfig.js'

export default {
  name:'a'+ Date.now(),
  data() {
    return {
      isHiddenOrgSelect: false,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false
      },
      formInfo: {}
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增团建活动',
        edit: '编辑团建活动',
        look: '组织团建活动'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '活动名称',
          keyName: 'activityName',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '举办组织',
          keyName: 'youthOrgId',
          viewName: 'youthOrgName',
          type: youthTreeSelect,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          hidden: this.isHiddenOrgSelect,
          attrs: {
            returnInitNode: true
          }
        },
        {
          label: '活动日期',
          keyName: 'activityTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          }
        },
        {
          label: '活动类型',
          keyName: 'activityTypeId',
          viewName: 'activityTypeName',
          type: Selector,
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          attrs: {
            urlType: 'union',
            selectType: 29
          }
        },
        {
          label: '活动地址',
          keyName: 'address',
          type: 'BaseInput',
          disabled: this.isDisabled,
          span: 16,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },

        {
          label: '负责人',
          keyName: 'principal',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '参加人',
          keyName: 'intervenor',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
            label: '活动概述',
            keyName: 'activitySummary',
            type: 'BaseTextarea',
            disabled: this.isDisabled,
            span: 24,
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '活动级别',
          keyName: 'activityLevel',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          slot: true,
          keyName: 'fileIds',
          label: '附图',
          isRequired: true
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    }
  },
  created() {
    this.initPage()
    this.getActivityDetailReq()
  },
  methods: {
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.formInfo = {
        ...this.formInfo,
        creatorName: userInfo.name,
        activityTime: curDate,
        createTime: curDate
      }
    },
    handleSelectOrg(key, data) {
      const { orgType, id } = data
      this.formInfo = {
        ...this.formInfo,
        youthOrgId: id,
        activityLevel: LEAGUE_TYPE_MAP[orgType]
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('youthOrgId')
      })
    },
    async getActivityDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          fileIds: res.data.fileInfoList || []
        }
        this.isHiddenOrgSelect = true
        this.$nextTick(() => {
          this.isHiddenOrgSelect = false
        })
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    getFileList(params) {
      if (!this.$route.query.id) {
        return Promise.resolve()
      }
      return getFiles({ ...params, query: { youthActivityId: this.$route.query.id, type: 2 } })
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.formItemList.forEach((item) => {
            if (item.isRequired && actionName === 'SUBMITTED' && !this.formInfo[item.keyName]?.length) {
              this.$message.warning(`请上传${item.label}`)
              throw new Error('break')
            }
          })
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const { addIds, delIds } = this.$refs.uploadTable.getChangedFileIds()
        const params = {
          ...this.formInfo,
          fileIds: (this.formInfo.fileIds && this.formInfo.fileIds.map((item) => item.commonId)) || [],
          status: actionName === 'SUBMITTED' ? 1 : 0,
          addRelatedFileIds: addIds,
          removeRelatedFileIds: delIds
        }
        const fn = this.pageType === 'add' ? addData : editData
        await fn(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        this.$refs.uploadTable.batchDeleteFile() // 删除文件
        this.$multiTab.close()
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    }
  }
}
</script>

<style lang="less" scoped>
.file-tips {
  color: #999999;
  padding-left: 50px;
}
</style>
